<template>
  <view class="flex flex-col flex-col-center-center" style="height: 70rpx">
    <tm-button
      :margin="[10]"
      size="small"
      :shadow="0"
      label="加入购物车"
      color="orange"
      @click="NumUpdate('+1')"
      v-if="!CartData || CartData.skuNum === 0"
    ></tm-button>
    <view class="flex flex-row flex-col-center-center" v-else>
      <tm-icon name="tmicon-minus-circle" color="grey" @click="NumUpdate('-1')"></tm-icon>
      <text class="text-grey" style="width: 60rpx; text-align: center">{{ CartData.skuNum }}</text>
      <tm-icon name="tmicon-plus-circle" class="mt-2" color="grey" @click="NumUpdate('+1')"></tm-icon>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useIndexStore } from '@/store/modules/IndexStore'
import tmButton from '../../tmui/components/tm-button/tm-button.vue'
import tmIcon from '@/tmui/components/tm-icon/tm-icon.vue'
import { onMounted, ref } from 'vue'
import type { CartItem } from '@/types/index'
const props = defineProps<{ skuId: string; perLimit: number; isCart?: boolean }>()
const IndexStore = useIndexStore()
const CartData = ref<CartItem>({})
onMounted(() => {
  let productData: CartItem = {}
  if (props.skuId) {
    productData = IndexStore.CartList.filter((ele) => ele.skuId._id === props.skuId)[0]
  } else {
    productData = IndexStore.CartList.filter((ele) => ele.skuId._id === IndexStore.skuId)[0]
  }
  CartData.value = productData
})
const NumUpdate = (type: string) => {
  uni.request({
    url: `http://localhost:3000/cart/addToCart/${props.skuId}/${type}`,
    success: (res) => {
      IndexStore.setCartList(res.data.cartList)
      CartData.value = res.data.cartList.filter((ele: CartItem) => ele.skuId._id === props.skuId)[0]
    },
  })
}
</script>

<style lang="less"></style>
